home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2037 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.3 KB

  1. Path: atglab.bls.com!Alun.Champion
  2. From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Trying to store a triangular matrix
  5. Date: 18 Jan 1996 17:48:45 GMT
  6. Organization: Computer People Inc.
  7. Message-ID: <ALUN.CHAMPION.96Jan18124845@g7240065.bridge.bst.bls.com>
  8. References: <sksen.821949883@merle>
  9. NNTP-Posting-Host: bstfirewall.bst.bls.com
  10. In-reply-to: sksen@merle.acns.nwu.edu's message of 18 Jan 96 07:24:43 GMT
  11.  
  12. In article <sksen.821949883@merle> sksen@merle.acns.nwu.edu (Subhro Sen) writes:
  13.  
  14. : I am trying to store a 2D lower triangular N x N matrix in
  15. : a 1D array...in other words i want A[i][j] to
  16. : map to some index m. What's the formula!?!?!
  17. : It's a lower triangular matrix, (A[i][j] = 0 for j > i)
  18. : i.e.:
  19.  
  20. : 1  0   0   0 
  21. : 2  1   0   0
  22. : 5  3   2   0
  23. : 9  3   4   1
  24.  
  25. : at first i had:
  26.  
  27. : m = i*N + j                where N=one dimension of matrix
  28.  
  29. try:
  30.     m = (i*(i+1))/2 + j;
  31.  
  32. Instead of having a algorithm to map to one dimensional array
  33. why not use a pointer to pointer like:
  34.  
  35.     int** a;
  36.     int i, j;
  37.  
  38.     a = malloc(sizeof(*a));
  39.     a[0] = malloc(sizeof(**a) * (N * (N + 1)) / 2);
  40.  
  41.     for (i = 1; i < N; i++)
  42.         a[i] = a[i-1] + i;
  43.  
  44. This has the advantage of using the reduced space but still gives means
  45. of accessing like:
  46.  
  47.     a[i][j] = 5;
  48.  
  49. But j must be <= i.
  50.  
  51. Regards
  52.  
  53.    -A.
  54. -- 
  55. | A.Champion                |
  56.